﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Activity.Data;
using Activity.Helper;
using Activity.Model;
using NHibernateVertica;
using Nancy.Extensions;

namespace Activity.API
{
    public class TimeTrackingSalePartReportHandler
    {
        public VerticaDataHelper Helper { get; set; } = new VerticaDataHelper();

        public IList<TimeTrackingSalePartReportModel.ListModel> GetReport(string ShopList, IList<TimeTrackingSalePartReportModel.TitleModel> TitleList)
        {
            try
            {
                var sql = $@"SELECT  *
FROM    ndw.ndw_timeTrackingSalePart_report
WHERE   Director != '加盟待定'
{(string.IsNullOrEmpty(ShopList)?"":$"AND ShopName IN ({ShopList})")}
ORDER BY ProvinceName ,
        Manager ,
        Director ,
        ShopName";
                var cmd = Helper.GetSqlStringCommand(sql);
                var dt = Helper.ExecuteDataTable(cmd);
                var list = CommHelper.ModelConvertHelper<TimeTrackingSalePartReportModel.NeceModel>.ConvertToModel(dt)
                    .ToList();
                list.ForEach(d =>
                {
                    d.Clossing = d?.KpiQty == 0 ? 0 : d?.SaleBillQty * 100 / (decimal?) d?.KpiQty;
                    d.UnitPrice = d?.SaleBillPartQty == 0 ? 0 : d?.FactPartAMT / d?.SaleBillPartQty;
                    d.SalelDv = d?.SaleBillPartQty == 0 ? 0 : d?.SalePartQty/ (decimal?)d?.SaleBillPartQty;
                });
                var group= list.GroupBy(d => new { d.ProvinceName, d.Director, d.Manager,d.ShopName });
                var newList = group.SelectMany(d => d).ToList();
                foreach (var item in group)
                {
                    var oldItem = item.Where(d => d.BillSegDate != "Date00tonow").Select(d => d).ToList();
                    if (oldItem.Count() < TitleList.Count())
                    {
                        //var titles = (from t in TitleList
                        //    where !(from o in oldItem
                        //        where t.BillSegDate == o.BillSegDate
                        //        select o.BillSegDate).Any()
                        //        select t.BillSegDate);
                        var titles = (from t in TitleList
                            select t.BillSegDate).Except(from o in oldItem
                            select o.BillSegDate).ToList();
                        foreach (var ti in titles)
                        {
                            var newItem = new TimeTrackingSalePartReportModel.NeceModel
                            {
                                BillSegDate = ti,
                                ProvinceName = oldItem.First().ProvinceName,
                                Director = oldItem.First().Director,
                                Manager = oldItem.First().Manager,
                                ShopName = oldItem.First().ShopName,
                            };
                            newList.Add(newItem);
                        }
                    }
                }
                var newGroup = newList.GroupBy(d => new {d.ProvinceName, d.Director, d.Manager});
                var result = newGroup.Select(d => new TimeTrackingSalePartReportModel.ListModel
                {
                    ProvinceName = d.Key.ProvinceName,
                    Director = d.Key.Director,
                    Manager = d.Key.Manager,
                    group = d.GroupBy(r => r.ProvinceName + "_" + r.Director + "_" + r.Manager + "_" + r.ShopName)
                        .ToList(),
                }).ToList();
                return result;
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }

        public IList<TimeTrackingSalePartReportModel.TitleModel> GetTitle()
        {
            try
            {
                var sql = @"SELECT  BillSegDate
FROM    ndw.ndw_timeTrackingSalePart_report
WHERE   BillSegDate != 'Date00tonow'
        AND BillSegDate is not null
GROUP BY BillSegDate
ORDER BY BillSegDate";
                var cmd = Helper.GetSqlStringCommand(sql);
                var dt = Helper.ExecuteDataTable(cmd);
                var list = CommHelper.ModelConvertHelper<TimeTrackingSalePartReportModel.TitleModel>.ConvertToModel(dt).ToList();
                list.ForEach(d => d.BillSegDateStr = title[d.BillSegDate]);
                return list;
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }

        public TimeTrackingSalePartReportModel.FinalModel FinalGet(string UserID)
        {
            try
            {
                var shopList = ConvertToStr(GetShopList(Convert.ToInt32(UserID)).ToList());
                var title = GetTitle();
                var list = GetReport(shopList, title);
                var result = new TimeTrackingSalePartReportModel.FinalModel
                {
                    title = title,
                    list = list,
                };
                return result;
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                return null;
            }
        }

        IList<string> GetShopList(int UserID)
        {
            var dc = new ActivityEntities();
            //TODO:获取当前用户店铺权限
            var query = (from a in dc.V_UserShopDataRights
                         where a.userid == UserID
                         select new
                         {
                             a.shopname
                         }).Distinct().Select(t => t.shopname).ToList();
            return query;
        }

        private string ConvertToStr(List<string> list)
        {
            if (list == null || list.Count == 0)
                return "";
            try
            {
                var sb = new StringBuilder();
                foreach (var t in list)
                {
                    sb.Append("'");
                    sb.Append(t);
                    sb.Append("'");
                    sb.Append(",");
                }
                if (sb.Length > 0)
                    sb.Remove(sb.Length - 1, 1);
                return sb.ToString();
            }
            catch (Exception)
            {
                return "";
            }
        }

        private Dictionary<string, string> title = new Dictionary<string, string>()
        {
            {"Date08to12", "8点至12点"},
            {"Date12to15", "12点至15点"},
            {"Date15to18", "15点至18点"},
            {"Date18to21", "18点至21点"},
            {"Date21to24", "21点至24点"},
        };

    }
}
